local cjson = require "cjson"
local _M = {}
_M._VERSION="0.1"

function _M:update_upstreams()
local http = require "resty.http"
local httpc = http:new()
        --生产10.42.28.27
       local resp,err = httpc:request_uri("http://10.42.27.29:38500",
{
    method = "GET",    ---请求方式    
    path="/v1/catalog/service/opf-message-push-online-message",--consul上对应的服务名称
	--path="/v1/catalog/service/smarthome-app-srv",

    --path="/search_product.htm?q=ipone",
    --query="q=iphone",    ---get方式传参数
    --body="name='jack'&age=18",    ---post方式传参数
    --path="/search_product.htm",    ----路径
    ---header参数
    --headers = {["User-Agent"]="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36"}
      headers = {
			["Content-Type"] = "application/x-www-form-urlencoded",
		}
})
if not resp then
    print("请求consul 失败!!!!!!!!!!!!!!!")
    return
end
if not resp.body then
    print("请求consul 失败!!!!!!!!!!!!!!!")
    return
end
resp=resp.body
 print("请求http请求返回结果为",resp)
 --ngx.log("请求http请求返回结果为"..cjson.encode(resp))
        --local resp = cjson.decode(resp);
resp = cjson.decode(resp)
        local upstreams = {}
        for i, v in ipairs(resp) do
        --ngx.log(ngx.ERR,"find consul service address"..v.ServiceAddress)
        upstreams[i] = {ip=v.ServiceAddress, port=3000}
        end
        ngx.shared.upstream_list:set("api_list", cjson.encode(upstreams))
end

function _M:get_upstreams()
   local upstreams_str = ngx.shared.upstream_list:get("api_list");
   local tmp_upstreams = cjson.decode(upstreams_str);
  -- print(upstreams_str);
   return tmp_upstreams;
end
return _M
